# coding=utf-8
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many


def record_cs() -> bool:
    # 获取ASAPI接口数据
    asapi_data = request_asapi(1, "CS", "2015-12-15", "DescribeClustersV1")
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for i in asapi_data['clusters']:
        tmp_tuple = (
            i['cluster_id'], i['name'], i['cluster_type'], i['init_version'], i['current_version'], i['docker_version'],
            i['network_mode'], i['vpc_id'], i['vswitch_id'], i['subnet_cidr'], i['size'], i['data_disk_category'],
            i['data_disk_size'], i['ResourceGroup'], i['ResourceGroupName'], i['Department'], i['DepartmentName'],
            i['state'], i['created'], i['updated'], datetime.now())
        values_list.append(tmp_tuple)
    table = 'c_cs_info'
    fields = "cluster_id,name,cluster_type,init_version,current_version,docker_version,network_mode,vpc_id,vswitch_id," \
             "subnet_cidr,size,data_disk_category,data_disk_size,resource_group,resource_group_name,department," \
             "department_name,state,created,updated,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_cs_info', methods=['POST'])
def record_cs_api():
    success = record_cs()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
